
package com.koron.util;

import com.koron.css2.ApplicationConfig;
import com.koron.css2.common.bean.FileProBean;
import com.koron.css2.common.bean.MultipartContentBean;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Title: Upload
 * Description:
 * @author DaiSn
 * @date 2019年3月13日
 */
public class Upload {

	private static final Map<String, String> FTOKEN = new ConcurrentHashMap<String, String>();

	public static void deleteFile(String path, HttpServletRequest request) {
		String temp = request.getSession().getServletContext().getRealPath("/");
		String clientPath = StringUtils.substringBefore(temp, "sanjiu");
		String finaPath = (clientPath + path).replace('\\', '/');
		File file = new File(finaPath + path);
		System.err.println(path);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				System.out.println("删除单个文件" + path + "成功！");

			} else {
				System.out.println("删除单个文件" + path + "失败！");

			}
		} else {
			System.out.println("删除单个文件失败：" + path + "不存在！");

		}
	}

	/**
	 * 执行文件上传 直接传文件 linux已测试
	 * 
	 * @param file
	 * @return
	 * @throws MalformedURLException
	 * @throws Exception
	 */
	public static Map<String, String> upLoad(MultipartFile[] files, int type) {
		String uploadPath = "";
		Map<String, String> map = new HashMap<String, String>();
		URL url = null;
		 String path = "C:\\upload\\uploadFile\\wmeter";// 上传文件夹
		// 用 当前日期+UUID作为文件名避免重名
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = sdf.format(new Date()).replaceAll("-", "");
		String name = dateStr + UUID.randomUUID().toString().replaceAll("-", "");//
		// 名称添加进返回Map中方便取出
		map.put("name", files[0].getOriginalFilename());
		for (int key = 0; key < files.length; key++) {
			MultipartFile file = files[key];
			// 获取文件类型，即后缀名
			String str = file.getOriginalFilename();
			String suffix = str.substring(str.lastIndexOf("."));
			// 绝对路径+生成的自动
			String finaPath = path + "/" + CommonUtils.getCurrentMonth().replaceAll("-", "") + name + (key) + suffix;
			uploadPath = path + "/" + CommonUtils.getCurrentMonth().replaceAll("-", "") + name + (key) + suffix;
			// 将uploadpath存入map中方便取出
			map.put("path", uploadPath);
			File uploadFile = new File(path);
			// 创建文件夹
			if (!uploadFile.exists()) {
				uploadFile.mkdirs();
			}
			try {
				file.transferTo(new File(finaPath));
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	public static String upload(MultipartFile file) throws Exception {
		Map<String, String> data = new HashMap<String, String>();
		FileProBean filePro = new FileProBean();
		List<MultipartContentBean> multipartContents = new ArrayList<MultipartContentBean>();
		MultipartContentBean multipartContent = new MultipartContentBean();
		multipartContent.setBytes(file.getBytes());
		multipartContent.setContentType(file.getContentType());
		multipartContent.setFileName(FilenameUtils.getName(file.getOriginalFilename()));
		multipartContents.add(multipartContent);
		String ftoken = getFToken();
		data.put("ftoken", ftoken);
		filePro.setData(data);
		filePro.setMultipart(multipartContents);
		String result = HttpUtils.upload(ApplicationConfig.getAccessoryUploadUrl() + "fileUpload", filePro);
		System.out.println("文件上传结果返回：{}"+ result.toString());
		MessageBean<?> message = com.koron.css2.serviceManage.utils.JsonUtils.jsonToPojo(result, MessageBean.class);
		if(message.getCode() != Constant.MESSAGE_INT_SUCCESS) {
			throw new RuntimeException("文件上传失败：" + message.getDescription());
		}
		Map<String, String> map = JsonUtils.objectToPojo(message.getData(), Map.class);
		return map.get("path");
	}

	public static String getFToken() throws Exception {
		if(FTOKEN.get("time") != null && (System.currentTimeMillis() - Long.parseLong(FTOKEN.get("time"))) < (30 * 60 * 1000)) {
			return FTOKEN.get("ftoken");
		}
		Map<String, String> data = new HashMap<String, String>();
		data.put("appid", ApplicationConfig.getAccessoryAppId());
		data.put("secret", ApplicationConfig.getAccessorySecret());
		String result = HttpUtils.sendPostJson(ApplicationConfig.getAccessoryUploadUrl() + "fileAuthorize", JsonUtils.objectToJson(data));
		System.out.println(("文件上传获取token结果返回：{}"+ result));
		MessageBean<?> message = JsonUtils.jsonToPojo(result, MessageBean.class);
		if(message.getCode() != Constant.MESSAGE_INT_SUCCESS) {
			throw new RuntimeException("获取 FTOKEN失败:" + message.getDescription());
		}
		Map<String, String> map = JsonUtils.objectToPojo(message.getData(), Map.class);
		FTOKEN.put("time", System.currentTimeMillis() + "");
		FTOKEN.put("ftoken", map.get("ftoken"));
		return map.get("ftoken");
	}

}
